package edu.hrbu.trade01.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.hrbu.trade01.entity.User;
import edu.hrbu.trade01.mapper.UserMapper;
import edu.hrbu.trade01.service.UserService;
import edu.hrbu.trade01.vo.UserLoginVo;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;

/**
 * @author 徐登宇
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    // 登录校验
    @Override
    public User login(UserLoginVo userLoginVo) {
        // 判断登录信息是否为空
        if (ObjectUtils.isEmpty(userLoginVo)
                || userLoginVo.getName() == null
                || userLoginVo.getPwd() == null) {
            return null;
        }
        // 判断是否与数据库信息匹配
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getName, userLoginVo.getName())
                .eq(User::getPwd, userLoginVo.getPwd());

        return getOne(queryWrapper);
    }

    // 条件分页查询
    @Override
    public Page<User> getPageWithCondition(int page, int limit, String userStr) {
        Page<User> pageParam = new Page<>(page, limit);
        LambdaQueryWrapper<User> wrapperUser = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(userStr)) {
            User userCondition = JSONUtil.toBean(userStr, User.class);
            if (userCondition != null) {
                String name = userCondition.getName();
                String sex = userCondition.getSex();
                String tel = userCondition.getTel();
                LocalDateTime createTime = userCondition.getCreateTime();
                LocalDateTime updateTime = userCondition.getUpdateTime();
                if (!ObjectUtils.isEmpty(name))
                    wrapperUser.like(User::getName, name);
                if (!ObjectUtils.isEmpty(sex))
                    wrapperUser.eq(User::getSex, sex);
                if (!ObjectUtils.isEmpty(tel))
                    wrapperUser.like(User::getTel, tel);
                if (!ObjectUtils.isEmpty(createTime))
                    wrapperUser.ge(User::getCreateTime, createTime);
                if (!ObjectUtils.isEmpty(updateTime))
                    wrapperUser.le(User::getUpdateTime, updateTime);
            }
        }
        return page(pageParam, wrapperUser);
    }

    // 添加修改前的用户名是否重复判断
    @Override
    public boolean check(User user) {
        LambdaQueryWrapper<User> wrapperUser = new LambdaQueryWrapper<>();
        if (user.getId() != null) {
            wrapperUser.ne(User::getId, user.getId());
        }
        wrapperUser.eq(User::getName, user.getName());
        return getOne(wrapperUser) == null;
    }
}
